package controllers

import (
	"fmt"
	"net/url"
	"os"

	"github.com/neo4j/neo4j-go-driver/v4/neo4j"
)

func (c *LoginController) Get() {
	c.TplName = "signin.html"
}

func (c *LoginController) Post() {
	username := c.GetString("username")
	password := c.GetString("password")
	remember := c.GetString("remember")
	driver, session := GetNeo4jConn()
	defer driver.Close()
	defer session.Close()
	result, _ := session.ReadTransaction(func(tx neo4j.Transaction) (interface{}, error) {
		records, err := tx.Run("match(n:User) where n.username=$username and n.password=$password return n.username as u", map[string]interface{}{"username": username, "password": password})
		if err != nil {
			panic(err)
		}
		if records.Next() { //验证通过
			if remember == "true" {
				c.Ctx.SetCookie("username", url.QueryEscape(username), 3600*24*10)
				c.Ctx.SetCookie("password", password, 3600*24*10)
			} else {
				c.Ctx.SetCookie("username", url.QueryEscape(username), 3600*24)
				c.Ctx.SetCookie("password", password, 3600*24)
			}
			return "1", err
		} else { //验证不通过
			return "0", err
		}

	})
	flag, _ := result.(string)
	c.Ctx.WriteString(flag)
}

func (c *RegisterController) Post() {
	username := c.GetString("username")
	password := c.GetString("password")
	driver, session := GetNeo4jConn()
	defer driver.Close()
	defer session.Close()
	result, _ := session.ReadTransaction(func(tx neo4j.Transaction) (interface{}, error) {
		records, err := tx.Run("match(n:User) where n.username=$username return n.username as u", map[string]interface{}{"username": username})
		if err != nil {
			panic(err)
		}
		if records.Next() {
			return 0, err //已被注册
		} else {
			return 1, err
		}
	})
	flag, _ := result.(int)
	if flag == 0 {
		c.Ctx.WriteString("0")
	} else {
		fmt.Println(username, password)
		_, _ = session.WriteTransaction(func(tx neo4j.Transaction) (interface{}, error) {
			r, e := tx.Run("create(n:User{username:$username,password:$password,privilege:'plain'})", map[string]interface{}{"username": username, "password": password})
			if e != nil {
				panic(e)
			}
			return r, e
		})
		err := os.Mkdir("user/"+username, 0777)
		if err != nil {
			panic(err)
		}
		c.Ctx.WriteString("1")
	}

}
